package com.example.lastwork.entity;

import com.example.lastwork.common.entity.LogicEntity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.util.Set;

@Entity
@Getter
@Setter
@Where(clause = "is_deleted = 0")
public class Orders extends LogicEntity {
    @Column
    private Double total;

    @Column
    private Integer status;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnoreProperties("orders")
    private Customer customer;

    @JsonIgnore
    @OneToMany(mappedBy = "orders",
            fetch = FetchType.LAZY,
            orphanRemoval = true,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties("orders")
    @JsonBackReference
    private Set<LineItem> lineItems;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnoreProperties("orders")
    private Shop shop;


    public LineItem addLineItem(String lineItemName){
        if (lineItems != null) {
            for (LineItem lineItem : lineItems) {
                if (lineItemName.equals(lineItem.getLineItemName())) {
                    lineItem.setQuantity(lineItem.getQuantity() + 1.0);
                    return lineItem;
                }
            }
        }
        LineItem lineItem = new LineItem();
        lineItem.setLineItemName(lineItemName);
        lineItem.setQuantity(1.0);
        lineItem.setOrders(this);
        lineItems.add(lineItem);

        return lineItem;
    }

    public LineItem minusLineItem(String lineItemName){
        if (lineItems != null) {
            for (LineItem lineItem : lineItems) {
                if (lineItemName.equals(lineItem.getLineItemName())) {
                    double currentQuantity = lineItem.getQuantity();
                    if (currentQuantity > 1.0) {
                        lineItem.setQuantity(currentQuantity - 1.0);
                        return lineItem;
                    } else {
                        lineItem.setQuantity(currentQuantity - 1.0);
                        lineItems.remove(lineItem);
                        lineItem.setOrders(null);
                        return lineItem;
                    }
                }
            }
        }
        return null;
    }
}
